package com.tender.config;

import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.List;

public class DynamicTableNameHandler implements TableNameHandler {
    // 需要动态处理的 table name 列表
    private final List<String> tableNames;

    private final String SUFFIX = "@ZX_HQ";

    private static final String IDENTIFIER = "LOCAL";

    public DynamicTableNameHandler(String ...tableNames) {
        this.tableNames = Arrays.asList(tableNames);
    }

    /************* 线程上线文 -- start **************/
    private static final ThreadLocal<String> HOLDER = new ThreadLocal<>();

    public static void setData() {
        HOLDER.set(IDENTIFIER);
    }

    public static String getData() {
        return HOLDER.get();
    }

    public static void clear() {
        HOLDER.remove();
    }
    /************* 线程上线文 -- end **************/

    private boolean need2ProcessTableName() {
        return StringUtils.isNotBlank(getData()) && StringUtils.equalsAnyIgnoreCase(IDENTIFIER, getData());
    }

    // 动态表名接口实现方法
    @Override
    public String dynamicTableName(String sql, String tableName) {
        if (this.tableNames.contains(tableName)){
            if (need2ProcessTableName()) {
                return tableName + SUFFIX;
            }
        }

        return tableName;
    }

}